<?php

class ridersController extends manageController {

    public function __construct() {
        if (!isset($_SESSION['zp_company']['islogin']) || empty($_SESSION['zp_company']['islogin'])) {
            Tools::AlertTxt('?md=company&cl=login&at=login', '请先登录');
            exit;
        }
    }


    public function riderslistAction() {
        $table = "riders";
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $func = (!empty($this->params['func'])) ? $this->params['func'] : '';
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $_phone = (!empty($this->params['_phone'])) ? (int) $this->params['_phone'] : '';
        $_name = (!empty($this->params['_name'])) ?  $this->params['_name'] : '';
        $_riders_status = (!empty($this->params['_riders_status'])) ? (int)$this->params['_riders_status'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("_phone", $_phone);
        $this->view->setVariable("_name", $_name);
        $this->view->setVariable("_riders_status", $_riders_status);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);

        $_p = (!empty($this->params['_p'])) ?  $this->params['_p'] : '999';
        $_c = (!empty($this->params['_c'])) ?  $this->params['_c'] : '999';
        $_a = (!empty($this->params['_a'])) ?  $this->params['_a'] : '999';


        // 骑手状态启停
        if (!empty($func) && $func == "status") {
            $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
            if ($id > 0) {
                $where_fields = array("AND" => array("=" => array("id" => $id)));
                $row = $this->model->getItemById($id, $table);
                $field = array();
                $field['initiate'] = $row['initiate'] == '1' ? '2' : '1';
                $field['update_id'] = $_SESSION['zp_company']['company_code'];
                $field['updatedt'] = 'now()';
                $r = $this->model->updateItem($field, $where_fields, $table);

                //日志
                $log = array();
                $log['table_id'] = $id;
                $log['table_name'] = $table;
                $log['type'] = 4;
                $log['page'] = "骑手状态";
                $log['content'] = $log['page'] . "：" . 1;
                $org = array();
                $this->model->setLog($log, $row, $field);
            }
           echo json_encode(array('status'=>1),JSON_UNESCAPED_UNICODE);
            exit;
        }


        // 删除骑手
        if (!empty($func) && $func == "del") {
            $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
            $field = array("isdeleted" => 1, 'update_id' => $_SESSION['zp_company']['company_code'], 'updatedt' => 'now()');
            $row = $this->model->getItemById($id, $table);
            $where_fields = array("AND" => array("=" => array("id" => $id)));
            $this->model->updateItem($field, $where_fields, $table);

            //日志
            $log = array();
            $log['table_id'] = $id;
            $log['table_name'] = $table;
            $log['type'] = 3;
            $log['page'] = "删除骑手";
            $log['content'] = $log['page'] . "：" . $this->params["id"];
            $this->model->setLog($log, $row, $field);
            echo json_encode(array('status'=>1),JSON_UNESCAPED_UNICODE);
            exit;
        }

        //抓列表
        $where = '(r.status = 1 OR r.status = 4) AND r.isdeleted = 0 ';  // 1=通过 4=禁止接单
//        $where = 'r.status = 1 AND r.isdeleted = 0 ';

        if($_riders_status){
            $where .=" AND r.initiate = $_riders_status";
        }
        if($_phone){
            $where .=" AND r.tel = $_phone";

        }
        if($_name){
            $where .=" AND r.name = '$_name'";
        }


        if($_p && $_p != 999){
            $where .=" AND service_province = '$_p'";

        }
        if($_c && $_c != 999){
            $where .=" AND service_city = '$_c'";
        }
        if($_a && $_a != 999){
            $where .=" AND service_area = '$_a'";
        }

        # 筛选所有地区
        $where_area = ['AND'=>['='=>['status'=>1,'isdeleted'=>0, 'is_parent'=>1,'parent_code'=>1]]];
        $Areas = $this->model->getItemByOther($where_area,'area');
        $sql = "SELECT r.* FROM riders as r LEFT JOIN xd_store as t ON t.store_id = r.service_shop_no where t.company_id = $CPCode AND $where ";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $rsp_list = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);


        $this->view->setVariable("_p", $_p);
        $this->view->setVariable("_c", $_c);
        $this->view->setVariable("_a", $_a);
        $this->view->setVariable("Areas", $Areas);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /**
     * 导出骑手列表
     */
    public function ExportExcelAction(){
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $_phone = (!empty($this->params['phone'])) ? (int) $this->params['phone'] : '';
        $_name = (!empty($this->params['name'])) ?  $this->params['name'] : '';
        $_riders_status = (!empty($this->params['riders_status'])) ? (int)$this->params['riders_status'] : '';
        $type = (!empty($this->params['type'])) ? (int)$this->params['type'] : '';
        if($type == 1){     # 正常骑手
            $where_fields = '(r.status = 1 OR r.status = 4) AND r.isdeleted = 0 ';  // 1=通过 4=禁止接单
            $tableName = '骑手表';
            $atname = 'riderslist';
        }elseif($type == 2){  # 待审核
            $where_fields = 'r.status = 0 AND r.isdeleted = 0 ';  // 0 = 待审核
            $tableName = '待审核骑手表';
            $atname = 'riders_audit_list';
        }else{  # 审核未通过
            $where_fields = '(r.status = 2 OR r.status = 3) AND r.isdeleted = 0 ';  // 0 = 待审核
            $tableName = '审核未通过骑手表';
            $atname = 'riders_no_pass_list';
        }

        if($_riders_status){
            $where_fields .=" AND r.initiate = $_riders_status ";
        }
        if($_phone){
            $where_fields .="  AND r.tel = $_phone ";

        }
        if($_name){
            $where_fields .=" AND r.name = $_name ";

        }

        $sql = "SELECT r.* FROM riders as r LEFT JOIN xd_store as t ON t.store_id = r.service_shop_no where t.company_id = $CPCode AND $where_fields ";

        $rsp_list = $this->model->getAny($sql);
        if (!empty($rsp_list)) {
            while ($row = mysqli_fetch_array($rsp_list, MYSQLI_ASSOC)) {
                $res[] = $row;
            }
        }

        if($res && is_array($res) && count($res) > 0) {
            foreach ($res as &$r) {
                $whereP = ['AND' => ['=' => ['status' => 1, 'isdeleted' => 0, 'code' => $r['province']]]];
                $whereC = ['AND' => ['=' => ['status' => 1, 'isdeleted' => 0, 'code' => $r['city']]]];
                $whereA = ['AND' => ['=' => ['status' => 1, 'isdeleted' => 0, 'code' => $r['area']]]];
                $whereServer = ['AND' => ['=' => ['status' => 1, 'isdeleted' => 0, 'code' => $r['service_province']]]];
                $p = $this->model->getItemByOther($whereP, 'area');
                $c = $this->model->getItemByOther($whereC, 'area');
                $a = $this->model->getItemByOther($whereA, 'area');
                $s = $this->model->getItemByOther($whereServer, 'area');
                $r['p'] = $p[0]['fullname'];
                $r['c'] = $c[0]['fullname'];
                $r['a'] = $a[0]['fullname'];
                $r['s'] = $s[0]['fullname'];
            }
            $titles = array('序号', '姓名', '性别', '昵称', '出生日期', '年龄', '电话', '省', '市', '区', '地址', '服务城市', '紧急联系人电话', '紧急联系人和本人关系', '紧急联系人', '身份证号', '异常次数', '启用状态', '审核状态');

            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles)."\n";
            foreach ($res as $key => $value) {
                $row = array();
                if ($value['status'] == 0) {
                    $status = '待审核';
                } elseif ($value['status'] == 1) {
                    $status = '通过';
                } elseif ($value['status'] == 2) {
                    $status = '驳回不得申请';
                } elseif ($value['status'] == 3) {
                    $status = '驳回重新申请';
                } else {
                    $status = '风控状态禁止接单，被指派';
                }
                if ($value['sex'] == 1) {
                    $sex = '男';
                } else {
                    $sex = '女';
                }

                if ($value['initiate'] == 1) {
                    $initiate = '启用';
                } else {
                    $initiate = '禁用';
                }

                $k = $key + 1;

                $row['id'] = $k;
                $row['name'] = $value['name'];
                $row['sex'] = $sex;
                $row['username'] = $value['username'];
                $row['birth_date'] = $value['birth_date'];
                $row['age'] = $value['age'];
                $row['tel'] = $value['tel'];
                $row['province'] = $value['p'];
                $row['city'] = $value['c'];
                $row['area'] = $value['a'];
                $row['address'] = $value['address'];
                $row['service_city'] = $value['s'];
                $row['urgency_cont_username_tel'] = $value['urgency_cont_username_tel'];
                $row['urgency_relation'] = $value['urgency_relation'];
                $row['urgency_cont_username'] = $value['urgency_cont_username'];
                $row['id_card'] = $value['id_card'];
                $row['error_count'] = $value['error_count'];
                $row['initiate'] = $initiate;
                $row['status'] = $status;
                echo implode("\t ,", $row) . "\n";
            }
            header('Content-Disposition: attachment; filename=' . $tableName. ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:application/vnd.ms-excel');
            ob_end_flush();
        }else{
            Tools::AlertTxt('?md=company&cl=riders&at='.$atname.'', '没有可汇出数据');
            exit;
        }

    }

    public function riderslist_checkAction(){
        $table = "riders";
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int) $this->params["page"];
        $exp_where['AND']['=']['id'] = $id;
        $rsp_list = $this->model->getItemById($id,$table);
        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['status'] = 1;
        $province = $this->model->getAll($where,'area',$orderby,$like_fields);
        $orderby = array('id' => 'asc');
        $like_fields = array();
//        $where['AND']['=']['status'] = 2;
//        $where['OR']['=']['status'] = 4;
//        $where['OR']['=']['status'] = 5;
        $where = ['AND'=>['='=>['isdeleted'=>0]]];
        $store = $this->model->getAll($where,'xd_store',$orderby,$like_fields);
        $this->view->setVariable("store", $store);
        $this->view->setVariable("province", $province);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function getImageAction(){
        $oldImage = json_decode($_POST['oldImage'],true);
        $fileObj = $_FILES['file'];
        $tmpName = $_FILES['file']['name'];
        $picName = strrchr($tmpName,'.');
        $str = rand(1,99999);
        $useName = date('Ymd').$str;
        $newName = $useName.$picName;
        $upload_path = 'webroot/admin/temp_img/';
        if($oldImage){
            $oldImage_filter  = array_filter($oldImage);
            $oldImage_unique  = array_unique($oldImage_filter);
            foreach($oldImage_unique as $v){
                if($v){
                    unlink($v);
                }
            }
        }
        if(!file_exists($upload_path)) {
            mkdir($upload_path, 0700);
        }
        move_uploaded_file($fileObj['tmp_name'],$upload_path.$newName);
        $data = ['img'=>$upload_path.$newName,'status'=>1];
        echo json_encode($data);

    }

    public function unlinkImageAction(){
        $dir = 'webroot/admin/temp_img/';
        if (!$handle = @opendir($dir)) {
            return false;
        }
        while (false !== ($file = readdir($handle))) {
            if ($file !== "." && $file !== "..") {
                $file = $dir . '/' . $file;
                if (is_dir($file)) {
                    deleteDir($file);
                } else {
                    @unlink($file);
                }
            }
        }
        @rmdir($dir);
        $data = ['status'=>1];
        echo json_encode($data);
    }


    /**
     * 骑手待审核
     */
    public function riders_audit_listAction() {
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $_phone = (!empty($this->params['_phone'])) ? (int) $this->params['_phone'] : '';
        $_name = (!empty($this->params['_name'])) ?  $this->params['_name'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("_phone", $_phone);
        $this->view->setVariable("_name", $_name);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        //抓列表
        $whereR = 'r.status = 0 AND r.isdeleted = 0 ';
        if($_phone){
            $whereR .=" AND r.tel = $_phone ";
        }
        if($_name){
            $whereR .=" AND r.name = $_name ";
        }
        $leftS = "LEFT JOIN xd_store as s ON r.service_shop_no = s.store_id";
        $sql = "SELECT r.*,s.storename as shop_name FROM riders as r LEFT JOIN xd_store as t ON t.store_id = r.service_shop_no $leftS where t.company_id = $CPCode AND $whereR ";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $rsp_list = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    public function riders_audit_list_checkAction(){
        $table = "riders";
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int) $this->params["page"];
        $exp_where['AND']['=']['id'] = $id;
        $rsp_list = $this->model->getItemById($id,$table);
        $orderby = array('id' => 'asc');
        $like_fields = array();
//        $where['AND']['=']['status'] = 2;
//        $where['OR']['=']['status'] = 4;
//        $where['OR']['=']['status'] = 5;
        $where = ['AND'=>['='=>['isdeleted'=>0]]];
        $store = $this->model->getAll($where,'xd_store',$orderby,$like_fields);
        foreach ($store as $s){
            if($rsp_list['service_shop_no'] == $s['store_id']){
                $rsp_list['shop_name'] = $s['storename'];
            }
        }

        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['parent_code'] = 1;
        $where_city['AND']['!=']['parent_code'] = 1;
        $where_city['AND']['=']['is_parent'] = 1;
        $where_area['AND']['=']['is_parent'] = 0;
        $province = $this->model->getAll($where,'area',$orderby,$like_fields);
        $city = $this->model->getAll($where_city,'area',$orderby,$like_fields);
        $area = $this->model->getAll($where_area,'area',$orderby,$like_fields);
        $service_province = $this->model->getAll($where,'area',$orderby,$like_fields);
        $service_city = $this->model->getAll($where_city,'area',$orderby,$like_fields);
        $service_area = $this->model->getAll($where_area,'area',$orderby,$like_fields);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("province", $province);
        $this->view->setVariable("area", $area);
        $this->view->setVariable("city", $city);

        $this->view->setVariable("service_province", $service_province);
        $this->view->setVariable("service_area", $service_area);
        $this->view->setVariable("service_city", $service_city);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function riders_audit_list_checkupdateAction(){
        $table = "riders";
        if (isset($_FILES['card_front_img']) && $_FILES['card_front_img']['name'] !== '') {
            $dir = $this->model->Uploaddir("riders/".$this->params['service_shop_no']);
            $upload_result = FileUpload::uploadSingle('card_front_img', 'riders_'.time().'f', '', $dir);
            if ($upload_result != "") {
                if ($upload_result == "filesize" || $upload_result == "fileext" || $upload_result == "fileupload") {
                    $msg = '档案过大或格式不符';
                    Tools::AlertTxt($url = '', $msg);
                } else {
                    $field['card_front_img'] = $this->params['service_shop_no'].'/'.$upload_result;
                }
            }
        }

        if (isset($_FILES['card_back_img']) && $_FILES['card_back_img']['name'] !== '') {
            $dir = $this->model->Uploaddir("riders/".$this->params['service_shop_no']);
            $upload_result = FileUpload::uploadSingle('card_back_img', 'riders_'.time().'b', '', $dir);
            if ($upload_result != "") {
                if ($upload_result == "filesize" || $upload_result == "fileext" || $upload_result == "fileupload") {
                    $msg = '档案过大或格式不符';
                    Tools::AlertTxt($url = '', $msg);
                } else {
                    $field['card_back_img'] = $this->params['service_shop_no'].'/'.$upload_result;
                }
            }
        }

        if (isset($_FILES['health_cards']) && $_FILES['health_cards']['name'] !== '') {
            $dir = $this->model->Uploaddir("riders/".$this->params['service_shop_no']);
            $upload_result = FileUpload::uploadSingle('health_cards', 'riders_'.time().'h', '', $dir);
            if ($upload_result != "") {
                if ($upload_result == "filesize" || $upload_result == "fileext" || $upload_result == "fileupload") {
                    $msg = '档案过大或格式不符';
                    Tools::AlertTxt($url = '', $msg);
                } else {
                    $field['health_cards'] = $this->params['service_shop_no'].'/'.$upload_result;
                }
            }
        }
        $field['id'] = $this->params["id"];
        $field['name'] = $this->params["name"];
        $field['username'] = $this->params["username"];
        $field['sex'] = $this->params["sex"];
        $field['username'] = $this->params["username"];
        $field['birth_date'] = $this->params["birth_date"];
        $field['age'] = $this->params["age"];
        $field['province'] = $this->params["province"];
        $field['city'] = $this->params["city"];
        $field['tel'] = $this->params["tel"];
        $field['area'] = $this->params["area"];
        $field['address'] = $this->params["address"];


        $field['service_province'] = $this->params["service_province"];
        $field['service_area'] = $this->params["service_area"];
        $field['service_city'] = $this->params["service_city"];


        $field['urgency_cont_username_tel'] = $this->params["urgency_cont_username_tel"];
        $field['urgency_relation'] = $this->params["urgency_relation"];
        $field['urgency_cont_username'] = $this->params["urgency_cont_username"];
        $field['resume'] = $this->params["resume"];
        $field['service_shop_no'] = $this->params["service_shop_no"];
        $field['id_card'] = $this->params["id_card"];
        $field['status'] = $this->params["audit"];
        $field['remark'] = $this->params["remark"];
        $field['initiate'] = 1;
        $org = $this->model->getItemById($this->params["id"], $table);
        $field["update_id"] = $_SESSION['zp_company']['uid'];
        $field['updatedt'] = 'now()';
        $where_fields = array("AND" => array("=" => array('id' => $this->params["id"], "isdeleted" => 0)));
        $r = $this->model->updateItem($field, $where_fields, $table);

        //日志
        $log = array();
        $log['table_id'] = $this->params["id"];
        $log['table_name'] = $table;
        $log['type'] = "UPDATE";
        $log['page'] = "审核骑手";
        $log['content'] = $log['page'] . "：" . 1;
        $this->model->setLog($log, $org, $field);

        $url = '?md=' . MvcReg::$_moduleName . '&cl=' . MvcReg::$_controllerName . '&at=riders_audit_list';
        Tools::AlertTxt($url, $this->getKeyWord('SAVE') . $this->getKeyWord('Msg_Successful'));
    }

    /**
     * 骑手审核未通过
     */
    public function riders_no_pass_listAction() {
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $_phone = (!empty($this->params['_phone'])) ? (int) $this->params['_phone'] : '';
        $_name = (!empty($this->params['_name'])) ?  $this->params['_name'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("_phone", $_phone);
        $this->view->setVariable("_name", $_name);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        //抓列表
        $whereR = 'r.isdeleted = 0 AND (r.status = 2 OR r.status = 3)';
        if($_phone){
            $whereR .="AND r.tel = $_phone";
        }
        if($_phone){
            $whereR .="AND r.name = $_name";
        }
        $leftS = "LEFT JOIN xd_store as s ON r.service_shop_no = s.store_id";
        $sql = "SELECT r.*,s.storename as shop_name FROM riders as r LEFT JOIN xd_store as t ON t.store_id = r.service_shop_no $leftS where t.company_id = $CPCode AND $whereR ";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $rsp_list = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function riders_no_pass_list_checkAction(){
        $table = "riders";
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int) $this->params["page"];
        $exp_where['AND']['=']['id'] = $id;
        $rsp_list = $this->model->getItemById($id,$table);

        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['status'] = 1;
        $province = $this->model->getAll($where,'area',$orderby,$like_fields);

        $this->view->setVariable("province", $province);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    public function getSAllAreaAction(){
        $service_province = empty($this->params["service_province"]) ? '0' : (int) $this->params["service_province"];
        $service_areaCode = empty($this->params["service_area"]) ? '0' : (int) $this->params["service_area"];
        $service_cityCode = empty($this->params["service_city"]) ? '0' : (int) $this->params["service_city"];

        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['parent_code'] = 1;
        $where_city['AND']['=']['parent_code'] = $service_province;
        $where_area['AND']['=']['parent_code'] = $service_cityCode;

        $province = $this->model->getAll($where,'area',$orderby,$like_fields);

        $city = $this->model->getAll($where_city,'area',$orderby,$like_fields);
        $area = $this->model->getAll($where_area,'area',$orderby,$like_fields);
        $data  = ['status'=>1,'province'=>$province,'city'=>$city,'area'=>$area];
        echo json_encode($data);
    }

    public function getAllAreaAction(){
        $province = empty($this->params["province"]) ? '0' : (int) $this->params["province"];
        $areaCode = empty($this->params["area"]) ? '0' : (int) $this->params["area"];
        $cityCode = empty($this->params["city"]) ? '0' : (int) $this->params["city"];

        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['parent_code'] = 1;
        $where_city['AND']['=']['parent_code'] = $province;
        $where_area['AND']['=']['parent_code'] = $cityCode;
        $province = $this->model->getAll($where,'area',$orderby,$like_fields);
        $city = $this->model->getAll($where_city,'area',$orderby,$like_fields);
        $area = $this->model->getAll($where_area,'area',$orderby,$like_fields);

        $data  = ['status'=>1,'province'=>$province,'city'=>$city,'area'=>$area];
        echo json_encode($data);
    }

    public function getCityAction(){
        $PCode = empty($this->params["code"]) ? '0' : (int) $this->params["code"];
        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['parent_code'] = $PCode;
        $city = $this->model->getAll($where,'area',$orderby,$like_fields);
        $data  = ['status'=>1,'city'=>$city];
        echo json_encode($data);
    }

    public function getAreaAction(){
        $CCode = empty($this->params["code"]) ? '0' : (int) $this->params["code"];
        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['parent_code'] = $CCode;
        $area = $this->model->getAll($where,'area',$orderby,$like_fields);
        $data  = ['status'=>1,'area'=>$area];
        echo json_encode($data);
    }

    public function getShopAction(){
        $SCode = empty($this->params["code"]) ? '0' : (int) $this->params["code"];
        $sql = "SELECT * FROM xd_store WHERE (status = 2 OR status = 4 OR status = 5) AND area = ".$SCode;
        $store = $this->model->getAny($sql);
        if (!empty($store)) {
            while ($Stores = mysqli_fetch_array($store, MYSQLI_ASSOC)) {
                $row[] = $Stores;
            }
        }
        $data  = ['status'=>1,'shop'=>$row];
        echo json_encode($data);
    }

    /**
     * 骑手运费
     */
    public function riders_freight_listAction() {
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $_phone = (!empty($this->params['_phone'])) ? (int) $this->params['_phone'] : '';
        $_name = (!empty($this->params['_name'])) ?  $this->params['_name'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $where = "";
        if($_phone){
            $where .= "a.express_mobile = $_phone AND ";
        }

        if($_name){
            $where .= "express_courier = '$_name' AND ";
        }
        $sql = "SELECT DISTINCT(a.express_courier) AS express_courier,a.id,a.express_mobile,SUM(a.express_fee) AS fee,COUNT(*) AS num,b.storename,b.front_city,b.front_area FROM orders_express AS a LEFT JOIN xd_store AS b ON a.shop_no = b.store_id WHERE $where  b.company_id = $CPCode AND a.isdeleted = 0 AND a.status = 5 AND a.express_type = 'self' GROUP BY  a.express_mobile";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $rsp_list = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        if (!empty($rsp_list)) {
            while ($row = mysqli_fetch_array($rsp_list, MYSQLI_ASSOC)) {
                $res[] = $row;
            }
        }
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("_phone", $_phone);
        $this->view->setVariable("_name", $_name);

        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /**
     * 骑手运费详情
     */
    public function riders_freight_list_checkAction() {
        $tel = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $_start = (!empty($this->params['_start'])) ?  $this->params['_start'] : '';
        $_end = (!empty($this->params['_end'])) ?  $this->params['_end'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        $where_fields = array("AND" => array("=" => array("isdeleted" => 0,'express_type'=>'self','status' => 5)));
        $where_fields['AND']['=']['express_mobile'] = $tel;


        $like_fields = array();
        $where_fields = "isdeleted=0 AND express_type='self' AND (status=5 OR status=6 OR status = 7)";
        $where_fields.=" AND express_mobile='$tel'";
        if($_start){
            $where_fields.= " AND shop_delivery_time >= '$_start'";
        }

        if($_end){
            $where_fields.= " AND shop_delivery_time < '$_end 23:59:59'";
        }

        $sql = "SELECT * FROM orders_express  WHERE $where_fields";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPages($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);


        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        $this->view->setVariable("express_courier", $rsp_list[0]['express_courier']);
        $this->view->setVariable("express_mobile", $tel);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("_start", $_start);
        $this->view->setVariable("_end", $_end);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/riders/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function getErrorAction(){
        $express_id = (!empty($this->params['id'])) ? (int)$this->params['id'] : '';   # id
        $r_e = $this->model->getItemById($express_id, 'orders_express');
        echo json_encode($r_e);
    }

    /**
     * 筛选城市
     */
    public function getCitysAction(){
        $parent_code = (!empty($this->params['code'])) ? (int)$this->params['code'] : '';
        $where = ['AND'=>['='=>['status'=>1,'isdeleted'=>0, 'parent_code'=>$parent_code]]];
        $p = $this->model->getItemByOther($where,'area');
        echo json_encode(['status'=>1,'msg'=>'','data'=>$p]);
    }

    /**
     * 筛选区
     */
    public function getAreasAction(){
        $parent_code = (!empty($this->params['code'])) ? (int)$this->params['code'] : '';
        $where = ['AND'=>['='=>['status'=>1,'isdeleted'=>0, 'parent_code'=>$parent_code]]];
        $p = $this->model->getItemByOther($where,'area');
        echo json_encode(['status'=>1,'msg'=>'','data'=>$p]);
    }
}

?>
